#include <iostream>
#include <unistd.h>
#include <cassert>
#include <sys/types.h>
#include <vector>

const int num = 5;
static int number = 1;
class channel
{
public:
    channel(int fd, pid_t id) : ctrlfd(fd), workerid(id)
    {
        name = "channel-1" + std::to_string(number++);
    }

public:
    int ctrlfd;
    pid_t workerid;
    std::string name;
};

void work()
{
    while (1)
    {
        // std::cout << "I am running:" << getpid() << std::endl;
        // sleep(1);

        int code = 0;
        ssize_t n = read(0, &code, sizeof(code));
        assert(n == sizeof(code));
    }
}

void CreatChannels(std::vector<channel> *c)
{
    for (int i = 0; i < num; i++)
    {
        int pipefd[2];
        int n = pipe(pipefd);
        assert(n == 0);

        pid_t id = fork();
        assert(id != -1);
        if (id == 0)
        {
            // 子进程
            close(pipefd[1]);
            dup2(pipefd[0], 0);
            work();

            exit(0);
        }

        // 父进程
        close(pipefd[0]);

        c->push_back(channel(pipefd[1], id));
    }
}

void PrintDebug(const std::vector<channel> &c)
{
    for (const auto &e : c)
    {
        std::cout << e.name << "," << e.ctrlfd << "," << e.workerid << std::endl;
    }
}

void SenfCommand(const std::vector<channel> &ch)
{
    int pos = 0;
    while (1)
    {
        // 1.选择任务
        int command = 1;
        // 2.选择信道（进程）
        const auto &c = ch[pos++];
        pos %= ch.size();
        // 3.发送任务
        write(c.ctrlfd, &command, sizeof(command));
    }
}

int main()
{
    std::vector<channel> channels;
    CreatChannels(&channels);
    // PrintDebug(channels);

    // 完成任务
    SendCommand(channels);

    return 0;
}